package com.yohann.boot.common.response;

import com.alibaba.fastjson.JSON;
import lombok.Getter;

import java.io.Serializable;

/**
 * <p>
 * 统一响应结果
 * </p>
 *
 * @author Yohann
 * @since 2020/9/21
 */
@Getter
public class Result<T> implements Serializable {
    private Boolean success;
    private Integer code;
    private String message;
    private T data;

    /**
     * 私有无参构造
     */
    private Result() {
    }

    /**
     * 通过结果枚举构造
     *
     * @param resultEnum 结果枚举
     */
    public Result(ResultEnum resultEnum) {
        this.success = true;
        this.code = resultEnum.getCode();
        this.message = resultEnum.getMessage();
    }

    /**
     * 无返回值 成功
     */
    public static Result<String> success() {
        Result<String> result = new Result<>();
        result.success(true)
                .code(ResultEnum.SUCCESS.getCode())
                .message(ResultEnum.SUCCESS.getMessage());

        return result;
    }

    /**
     * 失败
     */
    public static Result<String> error() {
        Result<String> result = new Result<>();
        result.success(false)
                .code(ResultEnum.ERROR.getCode())
                .message(ResultEnum.ERROR.getMessage());

        return result;
    }

    /**
     * 通过布尔状态字段返回
     *
     * @param state 状态
     */
    public static Result<String> state(boolean state) {
        return state ? Result.success() : Result.error();
    }

    /**
     * 通过布尔状态字段返回
     *
     * @param state      状态
     * @param successMsg 成功提示
     * @param errorMsg   错误提示
     */
    public static Result<String> state(boolean state, String successMsg, String errorMsg) {
        return state ? Result.success().message(successMsg) : Result.error().message(errorMsg);
    }

    /**
     * 有数据成功
     */
    public static <T> Result<T> success(T data) {
        Result<T> result = new Result<>(ResultEnum.SUCCESS);

        return result.data(data);
    }

    /**
     * 有数据失败
     */
    public static <T> Result<T> error(T data) {
        Result<T> result = new Result<>(ResultEnum.ERROR);

        return result.data(data);
    }

    public Result<T> success(Boolean success) {
        this.success = success;

        return this;
    }

    public Result<T> message(String message) {
        this.message = message;

        return this;
    }

    public Result<T> code(Integer code) {
        this.code = code;

        return this;
    }

    private Result<T> data(T data) {
        this.data = data;

        return this;
    }

    /**
     * 结果序列化为json
     */
    private String toJsonString() {
        return JSON.toJSONString(this);
    }
}